package com.rocbrid.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rocbrid.common.R;
import com.rocbrid.exception.BizException;
import com.rocbrid.pojo.User;
import com.rocbrid.service.UserService;
import com.rocbrid.utils.JwtUtil;
import com.rocbrid.utils.Md5Util;
import com.rocbrid.utils.ThreadLocalUtil;
import com.rocbrid.vo.req.UserRegisterVo;
import com.rocbrid.vo.req.UserUpdateVo;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.rocbrid.exception.BizExceptionEnum.USER_REGISTER_MRROR;

@Slf4j
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 跟新密码
     * @param old_pwd
     * @param new_pwd
     * @param re_pwd
     * @return
     */
    @PatchMapping("/updatePwd")
    public R updateUserPwd(@Param("old_pwd") @NotNull String old_pwd,
                           @Param("new_pwd") @NotNull String new_pwd,
                           @Param("re_pwd")@NotNull String re_pwd) {

        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        User userServiceById = userService.getById(id);
        log.info("查询到的原密码{}",userServiceById);
        if (!Md5Util.checkPassword(old_pwd,userServiceById.getPassword())) {
            return R.error("原密码不正确");
        }
        User user = new User();
        user.setId(id);
        user.setPassword(Md5Util.getMD5String(re_pwd));
         userService.updateById(user);
        return R.ok("密码跟新成功");
    }

    /**
     * 更新头像
     *
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public R updateAvatar(@RequestParam("avatarUrl") @URL(message = "地址错误") String avatarUrl) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        User user = new User();
        user.setId(id);
        user.setUserPic(avatarUrl);
        userService.updateById(user);
        return R.ok();

    }

    /**
     * 跟新用户信息
     *
     * @param userUpdateVo
     * @return
     */
    @PutMapping("/update")
    public R updateUser(@RequestBody @Valid UserUpdateVo userUpdateVo) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateVo, user);
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 获取用户想象信息
     *
     * @return
     */
    @GetMapping("/userinfo")
    public R getUserInfo() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        QueryWrapper<User> userInfoWrapper = new QueryWrapper<>();
        userInfoWrapper.eq("id", id);
        User userInfo = userService.getOne(userInfoWrapper);
        return R.ok(userInfo);
    }

    /**
     * 登录
     *
     * @param userRegisterVo
     * @return
     */
    @PostMapping("/login")
    public R login(@Valid UserRegisterVo userRegisterVo) {
        log.info("用户{}进行登录请求", userRegisterVo.getUsername());
        //查询用户名是否存在
        QueryWrapper<User> userVoQueryWrapper = new QueryWrapper<>();
        userVoQueryWrapper.eq("username", userRegisterVo.getUsername());
        User one = userService.getOne(userVoQueryWrapper);
        if (one == null) {
            return R.error(1001, "用户名不正确");
        }
        if (Md5Util.getMD5String(userRegisterVo.getPassword()).equals(one.getPassword())) {
            //登录成功
            log.info("用户{}登录成功", userRegisterVo.getUsername());
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", one.getId());
            claims.put("username", one.getUsername());
            String token = JwtUtil.genToken(claims);
            return R.ok("登录成功", token);
        }
        return R.error(1, "登录失败,用户名或者密码不正确");
    }

    /**
     * 注册功能
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R registerUser(@RequestBody @Valid UserRegisterVo user) {
        log.info("用户{}进行注册请求", user.getUsername());
        //先查询是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User one = userService.getOne(userQueryWrapper);
        if (one == null) {
            //注册成功
            //对密码进行加密处理
            String md5String = Md5Util.getMD5String(user.getPassword());
            user.setPassword(md5String);
            User userDo = new User();
            //vo转Do
            BeanUtils.copyProperties(user, userDo);
            userService.save(userDo);
            return R.ok();
        }
        //用户如果存在抛出一个业务异常
        throw new BizException(USER_REGISTER_MRROR);


    }

}
